<template>
    <el-card>
        <template #header>
            <span>新密码设置</span>
        </template>
        <el-col :span="8">
            <el-form label-width="80px" :model="passForm" :rules="rules" ref="formIns">
                <el-form-item label="原密码" prop="password">
                    <el-input type="password" v-model="passForm.password" />
                </el-form-item>
                <el-form-item label="新密码" prop="newpass">
                    <el-input type="password" v-model="passForm.newpass" />
                </el-form-item>
                <el-form-item label="确认密码" prop="repass">
                    <el-input type="password" v-model="passForm.repass" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleChange">确认修改</el-button>
                </el-form-item>
            </el-form>
        </el-col>
    </el-card>
</template>
<script setup lang="ts">
import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus"
import { ElMessage } from 'element-plus'
import { password } from "@/api/api";
const passForm = reactive<PassForm>({
    id: sessionStorage.getItem('userid') as string,
    password: "",
    newpass: "",
    repass: ""
})
const passValiFn = (field: any, value: string, cb: any) => {
    let reg = /^[0-9a-zA-Z]{6,}$/;
    if (reg.test(value)) {
        cb();
    } else {
        cb(new Error("新密码必须是由6为以上的数字或字母组成"));
    }
}
const repassValiFn = (field: any, value: string, cb: any) => {
    if (value !== passForm.newpass) {
        cb(new Error("两次密码需保持一致"));
    } else {
        cb();
    }
}
const rules: FormRules = {
    password: { required: true, message: "请输入密码", trigger: 'blur' },
    newpass: [
        { required: true, message: "请输入新密码", trigger: 'blur' },
        { validator: passValiFn, trigger: 'blur' }
    ],
    repass: [
        { required: true, message: "请再次输入新密码", trigger: 'blur' },
        { validator: repassValiFn, trigger: 'blur' }
    ],
}
const formIns = ref<FormInstance>();
const handleChange = async () => {
    try {
        await formIns.value?.validate();
        const res=await password(passForm);
        if(res.data.code===200){
            ElMessage.success("密码修改成功");
            formIns.value?.resetFields();
        }else{
            ElMessage.error("密码修改失败")
        }
    } 
    catch (error) {
        console.log(error)
    }
}
</script>
<style scoped></style>